package javaweb.utility;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author shkstart
 * @creat -07-13 12:17
 */
public class JDBCUnility {

private static DruidDataSource dd;
private static ThreadLocal<Connection> conns=new ThreadLocal();
   static {

        try {
            Properties ps = new Properties();
            InputStream resourceAsStream = JDBCUnility.class.getClassLoader().getResourceAsStream("durid.properties");
            ps.load(resourceAsStream);
            dd= (DruidDataSource) DruidDataSourceFactory.createDataSource(ps);
            DruidPooledConnection conn = dd.getConnection();
            //System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static Connection getConnection() {
        Connection conn = conns.get();
        if (conn == null) {
            try {
                conn = dd.getConnection();
                conns.set(conn);
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    return conn;
   }
//public static void closeConnection(Connection conn){
//
//       if (conn!=null){
//           try {
//               conn.close();
//           } catch (SQLException e) {
//               e.printStackTrace();
//           }
//       }
//}

public static void closeAndCommit(){
    Connection connection = conns.get();
    if (connection!=null){
        try {
            connection.commit();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
conns.remove();
}
public static void closeAndRollback(){
    Connection connection = conns.get();
    if (connection!=null){
        try {
            connection.rollback();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    conns.remove();
}
}

